package cn.iocoder.yudao.module.vlog.product.service;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.module.api.product.spu.ProductSpuApi;
import cn.iocoder.yudao.module.api.product.spu.dto.ProductSpuRespDTO;
import cn.iocoder.yudao.module.vlog.product.dal.dataobject.VLogProductDO;
import cn.iocoder.yudao.module.vlog.product.dal.mysql.VLogProductMapper;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 视频带货 Service 实现类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Service
@Validated
public class VLogProductServiceImpl implements VLogProductService {

    @Resource
    private VLogProductMapper vLogProductMapper;

    @Resource
    private ProductSpuApi productSpuApi;

    @Override
    public Map<Long, Collection<ProductSpuRespDTO>> getProductSpuMap(@NonNull Collection<Long> vlogIds, @Nullable Integer limit) {
        if (CollUtil.isEmpty(vlogIds)) {
            return new HashMap<>();
        }
        CoreLambdaQueryWrapper<VLogProductDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.inIfPresent(VLogProductDO::getVlogId, vlogIds);
        wrapper.limitN(limit == null || limit < 1 ? 1 : limit);
        List<VLogProductDO> list = vLogProductMapper.selectList(wrapper);
        Set<Long> spuIds = list.stream().map(VLogProductDO::getSpuId).collect(Collectors.toSet());
        List<ProductSpuRespDTO> spus = productSpuApi.getSpuList(spuIds);
        Map<Long, Collection<ProductSpuRespDTO>> map = new HashMap<>();
        for (VLogProductDO product : list) {
            Collection<ProductSpuRespDTO> collection;
            if (map.containsKey(product.getVlogId())) {
                collection = map.get(product.getVlogId());
            } else {
                collection = new ArrayList<>();
                map.put(product.getVlogId(), collection);
            }
            for (ProductSpuRespDTO spu : spus) {
                if (Objects.equals(product.getSpuId(), spu.getId())) {
                    collection.add(spu);
                    break;
                }
            }
        }
        return map;
    }

    @Override
    public Set<Long> getProductSpuIds(@NonNull Long userId, @NonNull Long shopId, @NonNull Long vlogId, Integer limit) {
        CoreLambdaQueryWrapper<VLogProductDO> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(VLogProductDO::getVlogId, vlogId);
        wrapper.limitN(limit == null || limit < 1 ? 1 : limit);
        List<VLogProductDO> list = vLogProductMapper.selectList(wrapper);
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newHashSet();
        }
        return list.stream().map(VLogProductDO::getSpuId).collect(Collectors.toSet());
    }

}
